/**
 * 
 */
package com.yi.backend.db.api.impl;

import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.yi.backend.db.api.IMongoDBHelperApi;
import com.yi.backend.db.mongo.MongoConnection;

/**
 * @author long
 * 
 */
public class MongoDBHelperApi implements IMongoDBHelperApi {

	private MongoConnection conn;

	@Override
	public void createDBTableByName(String schemaName) throws MongoException {
		// TODO Auto-generated method stub
		conn.getDb().createCollection(schemaName, null);
	}

	@Override
	public String create(String schemaName, DBObject dbObject)
			throws MongoException {
		// TODO Auto-generated method stub
		DBObject exist = conn.getCollection(schemaName).findOne(
				new BasicDBObject(MongoDBConstants.nameCol, dbObject
						.get(MongoDBConstants.nameCol)));
		if (exist != null)
			return exist.get(MongoDBConstants.idCol).toString();
		conn.getCollection(schemaName).insert(dbObject);
		return dbObject.get(MongoDBConstants.idCol).toString();
	}

	@Override
	public void update(String schemaName, DBObject dbObject)
			throws MongoException {
		// TODO Auto-generated method stub
		conn.getCollection(schemaName).update(
				new BasicDBObject(MongoDBConstants.idCol,
						dbObject.get(MongoDBConstants.idCol)), dbObject);
	}

	@Override
	public DBObject viewById(String schemaName, String modelId)
			throws MongoException {
		// TODO Auto-generated method stub
		return conn.getCollection(schemaName).findOne(
				new BasicDBObject(MongoDBConstants.idCol, modelId));
	}

	@Override
	public DBObject viewByName(String schemaName, String modelName)
			throws MongoException {
		// TODO Auto-generated method stub
		return conn.getCollection(schemaName).findOne(
				new BasicDBObject(MongoDBConstants.nameCol, modelName));
	}
	
	@Override
	public Object viewFieldById(final String schemaName, final String modelId,
			final String fieldName) throws MongoException {
		return conn.getCollection(schemaName)
				.findOne(new BasicDBObject(MongoDBConstants.idCol, modelId))
				.get(fieldName);
	}
	@Override
	public Object viewFieldByName(final String schemaName, final String modelName,
			final String fieldName) throws MongoException {
		return conn.getCollection(schemaName)
				.findOne(new BasicDBObject(MongoDBConstants.nameCol, modelName))
				.get(fieldName);
	}
	
	@Override
	public void removeById(String schemaName, String modelId)
			throws MongoException {
		// TODO Auto-generated method stub
		conn.getCollection(schemaName).remove(
				new BasicDBObject(MongoDBConstants.idCol, modelId));
	}

	@Override
	public List<DBObject> list(String schemaName, int pageNumber)
			throws MongoException {
		// TODO Auto-generated method stub
		return null;
	}

	public MongoConnection getConn() {
		return conn;
	}

	public void setConn(MongoConnection conn) {
		this.conn = conn;
	}

}
